package com.health.filter;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.health.vo.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.Duration;

@Component
public class LoginFilter implements Filter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取请求头中的Token
        String token = request.getHeader("token");
        //响应的数据
        Result result = null;

        if(!StringUtils.isEmpty(token)){
            //判断Token是否存在
            Boolean hasKey = redisTemplate.hasKey(token);
            if(hasKey != null && hasKey){
                //token令牌认证成功

                //续约，重置Token令牌的有效时间
                redisTemplate.expire(token, Duration.ofMinutes(30));
                //过滤器放行
                filterChain.doFilter(servletRequest, servletResponse);
                //停止代码继续运行
                return;
            }else{
                //Token错误
                result = new Result(false,"Token错误", 1001);
            }
        }else{
            //未携带Token
            result = new Result(false,"Token未传递", 1001);
        }

        //响应数据
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("html/text;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(result));
    }
}
